import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  /**
   * 调用主进程方法
   * @param {string} channel - IPC通道名称
   * @param {...any} args - 参数
   * @returns {Promise<any>}
   */
  invoke: function (channel, ...args) {
    // 允许的通道白名单
    const validChannels = ['app:getVersion']
    console.log('invoke', channel, args)
    if (validChannels.includes(channel)) {
      return ipcRenderer.invoke(channel, ...args)
    }
    
    throw new Error(`Invalid IPC channel: ${channel}`)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}